import React, { useState, useEffect, useRef, Suspense } from 'react';
import { useDispatch, useSelector } from "react-redux"
import { addUser, addUserAsync, userListQuery } from "../store/userSlice"
import Loading2 from '@/components/loading/Loading2';

const randomId = (minimum=0, maximum=10) => {
    minimum = minimum || 0
    maximum = maximum || 10

    return Math.floor(Math.random() * (maximum - minimum + 1)) + minimum
}


const UserList = ({ users }) => {

    return (
        <ul className="mt-10">
            {
                users && users.map(item => {
                    return (
                        <li key={item.id} className="mb-10">
                            <p>{item.first_name} {item.last_name}</p>
                            <p>{item.email}</p>
                            <p><img src={item.avatar} /></p>
                        </li>
                    )
                })
            }
        </ul>
    )
}


export const ReduxApp = () => {

    const dispatch = useDispatch()
    const users = useSelector(state => state.user.users)


    const handleAddUser = () => {
        const id = Date.now()
        let data = {
            id: Date.now() + Math.random(),
            first_name: `Echo ${id}`,
            last_name: `Bluth ${id}`,
            avatar: "https://reqres.in/img/faces/1-image.jpg",
            email: "george.bluth@reqres.in"

        }

        // dispatch(addUser(data))

        // 使用异步方法
        dispatch(addUserAsync(data))
    }

    const handleUserListQuery = () => {
        const pageId = randomId(1, 2)
        dispatch(userListQuery(pageId))
    }



    console.log('ReduxApp render...');
    return (
        <>
            <h1>ReduxApp</h1>
            <div>
                <p>
                    <button onClick={handleAddUser}>新增用户</button>
                    <button onClick={handleUserListQuery}>查询用户</button>
                </p>
            </div>

            <UserList users={users} />
        </>
    )
}
